<template>
  <el-container>
    <el-aside style="float:left;width: 300px;">
      <el-card class="box-card el-card-flex">
        <!--树状图搜索框 -->
        <div slot="header" class="clearfix">
          <el-input placeholder="按机构名称查询" suffix-icon="el-icon-search" v-model="filterText" clearable></el-input>
        </div>
        <!-- 树状图 -->
        <div class="text item el-over-auto">
          <el-tree :highlight-current="true" class="filter-tree" :data="dataTree" v-show="filterText"
            default-expand-all :load="loadNode" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="orgId" @node-click="handleNodeClick"></el-tree>
          <el-tree :highlight-current="true" class="filter-tree" v-show="filterText=='' " :load="loadNode"
            :default-expanded-keys="treeExpandedKey" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="orgId" lazy @node-click="handleNodeClick" :key="keyTree"></el-tree>
        </div>
      </el-card>
    </el-aside>
    <el-main style="padding:0 0 0 10px;">
      <!-- 卡片 -->
      <el-card class="box-card el-card-flex">
        <div slot="header" class="clearfix">
          <span>
            <i class="el-icon-menu"></i>
            人员信息
          </span>
        </div>
        <!-- 表格 -->
        <div class="text item el-over-auto">
          <div class="demo-form-inline" style="float: left;height:43px">
            <!-- 员工搜索 -->
            <el-input clearable v-model="personalSearch" placeholder="请输入员工姓名" style="width:200px;" @keyup.enter.native="justSearchPeople()"
              @clear="initSearchList()">
              <el-button slot="append" icon="el-icon-search" @click="justSearchPeople()"></el-button>
            </el-input>
            <el-button plain type="primary" style="float: right;margin-right:5px; margin-left:5px" class="el-button-pad"
              @click="handleAdd('editData')">新增<i class="el-icon-plus el-icon--right"></i>
            </el-button>
            <el-button plain type="primary" style="float: right;margin-right: 5px; margin-left:5px" class="el-button-pad"
              @click="excelDownload()">
              导入模板下载
              <i class="el-icon-download el-icon--right"></i>
            </el-button>
            <div style="float: right;margin-right: 5px;">
              <el-upload class="upload-demo" ref="upload" action="/api/ccms/org/employee/importExcel" :headers="{Authorization: this.Authorization}"
                :show-file-list='false' :on-success="handleSuccess" :before-upload='handleBefore' :file-list="fileList">
                <el-button slot="trigger" plain size="small" type="primary">批量上传<i class="el-icon-upload el-icon--right"></i></el-button>
              </el-upload>
            </div>
          </div>
          <el-table border height="100%" style="border-bottom: 40px solid transparent;" :data="tableData" stripe ref="tableData">
            <el-table-column type="index" min-width="100px" label="序号" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="empName" min-width="100px" label="人员姓名" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="empCode" min-width="100px" label="人员代码" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="gender" min-width="100px" label="性别" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="empStatus" min-width="100px" label="人员状态" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="userName" min-width="100px" label="用户名" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="mobileNo" min-width="100px" label="手机号" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column min-width="200px" prop="positions" label="归属关系" align="left">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>{{scope.row.postionsAry?scope.row.postionsAry.join('/'):''}}</p>
                  <div slot="reference" class="table-title-word">
                    <el-tag style="cursor: pointer;" size="mini" :key=index v-for="(item,index) in scope.row.positions">{{item.shortName?item.shortName:item.posiName}}
                    </el-tag>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="control" align="center" width="110px" label="操作" fixed="right">
              <template slot-scope="scope">
                <el-button title="编辑" class="td-btn-icon" type="text" @click="handleEdit(scope.$index, scope.row)"><i
                    class="el-icon-edit"></i></el-button>
                <el-button title="岗位编辑" class="td-btn-icon" type="text" @click="handlePeopleEdit(scope.$index, scope.row)"><i
                    class="el-icon-medal"></i></el-button>
              </template>
            </el-table-column>
            <el-table-column prop="order" align="center" label="排序" fixed="right">
              <template slot-scope="scope">
                <el-button class="td-btn-icon" type="text" v-if="scope.$index != 0" @click="handleUp(scope.$index, scope.row, 'up')"><i
                    class="el-icon-top"></i></el-button>
                <el-button class="td-btn-icon" type="text" v-if="scope.$index != tableData.length-1" @click="handleUp(scope.$index, scope.row, 'down')"><i
                    class="el-icon-bottom"></i></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            background :current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total"></el-pagination>
          <!-- 编辑/新增弹框 -->
          <el-dialog :title="changeTitle" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogVisible"
            @close="handleClose('editData')">
            <el-form label-width="150px" ref="editData" :model="editData">
              <el-form-item label="人员姓名" prop="empName" :rules="{required: true, message: '请填写人员姓名'}">
                <el-col :span="12">
                  <el-input v-model="editData.empName" auto-complete="off" placeholder="请填写人员姓名"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="人员代码" prop="empCode" :rules="{required: true, message: '请输入人员代码'}">
                <el-col :span="18">
                  <el-input v-model="editData.empCode" auto-complete="off" placeholder="请填写人员代码" :disabled='changeTitle=="编辑人员"?true:false'></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="头像">
                <el-upload action="/api/ccms/fileupload/file/upload" list-type="picture-card" :headers="{Authorization: this.Authorization}"
                  :on-success='photoSuccess' :before-upload='beforeAvatarUpload' :on-change="handleAvatarChange" :file-list="photoFileList">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="photos" alt="">
                    <span class="el-upload-list__item-actions">
                      <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="归属关系" ref='addPositons' :rules="{required: true, message: '请选归属关系'}" prop="positions"
                class="el-form-tag">
                <el-col :span="24">
                  <el-tag class='job-tag' size="medium" style="cursor: pointer;" :title="changeTitle=='编辑人员'?item.fullName.split(',').join('-') +'-'+item.posiName:item.fullName + item.posiName"
                    v-for="(item,index) in editData.positions" :key='index'>{{item.shortName}}</el-tag>
                  <el-button @click="tagAdd"> 分配岗位 <i class="el-icon-upload el-icon-plus"></i></el-button>
                </el-col>
              </el-form-item>
              <el-form-item label="性别" prop="genderId" :rules="{required: true, message:'请选择性别'}">
                <el-col :span="24">
                  <el-radio-group v-model="editData.genderId">
                    <el-radio v-for="item in addGender" :key="item.id" :label="item.id" placeholder="请选择性别" border>{{item.name}}</el-radio>
                  </el-radio-group>
                </el-col>
              </el-form-item>
              <el-form-item label="人员状态" prop="empStatusId" :rules="{required: true, message: '请选择人员状态'}">
                <el-col :span="24">
                  <el-radio-group v-model="editData.empStatusId" placeholder="请选择人员状态">
                    <el-radio v-for="item in addUser" :key="item.id" :label="item.id" placeholder="请选择人员状态" border>{{item.name}}</el-radio>
                  </el-radio-group>
                </el-col>
              </el-form-item>
              <el-form-item label="用户名" prop="userName">
                <el-col :span="18">
                  <el-input v-model="editData.userName" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="电话号码" prop="mobileNo" :rules="{required: true, message: '请输入电话号码'}">
                <el-col :span="18">
                  <el-input v-model="editData.mobileNo" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handleCheck('editData')">保 存 <i class="el-icon-document-checked"></i></el-button>
              <el-button type="danger" @click="handleCheckClose('editData')">关 闭 <i class="el-icon-close"></i></el-button>
            </span>
          </el-dialog>
        </div>
      </el-card>
    </el-main>
    <PeopleEdit :dialogPeople="dialogPeople" :initialeditData='initialeditData' @peopleDialog="peopleDialog" @jobEdit="jobEdit"
      :editDataEdit='editData' :changeTitle='changeTitle' @refreshTable="refreshTable" :justJobEdit='justJobEdit'></PeopleEdit>
  </el-container>
</template>
<script>
  import {
    Tree,
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Tag,
    Upload,
    Popover
  } from 'element-ui'
  import {
    organizationParent,
    organizationSearch,
    organizationRoot,
    orgEmpOrgOrgId,
    employeeSearch,
    empPositionPositionId,
    employeeSort,
    employeeAddOrEdit,
    comboBoxDataSelect,
    empPositionRelation,
    orgPositionListsDatas,
    employeeSearchOrgId,
    employeeEmpId,
    upDownRemove,
    photoDel
  } from '@/api/org/peoplemanage/peoplemanage.js'
  import {
  	attachPath //附件绝对地址
  } from '@/api/attachCommon/attachCommon.js'
  import PeopleEdit from './peopleEdit.vue'
  export default {
    name: 'peoplemanage',
    components: {
      'el-tree': Tree, //树形菜单
      'el-dialog': Dialog, //对话框
      'el-table': Table, //表格
      'el-table-column': TableColumn, //表格列
      'el-pagination': Pagination, //分页
      'el-tag': Tag, //标签
      'el-upload': Upload,
      'el-popover': Popover,
      PeopleEdit
    },

    data() {
      return {
        photos:'',
        realPhotoUrL: '',
        photoFileList: [],
        disabled: false,
        dialogPic: false,
        uploadDatas: '',
        readonly: false,
        treeExpandedKey: [],
        changeTitle: "",
        keyTree: 1,
        filterText: '',
        dataTree: [], //树形图初始化
        defaultProps: {
          label: 'orgName',
          isLeaf: 'leaf'
        },
        showBtton: false,
        dialogVisible: false, //岗位编辑弹框
        dialogAdd: false,
        pageSize: 20,
        total: 0,
        Authorization: '',
        editData: {
          "empName": "",
          "empCode": "",
          "genderId": "",
          "empStatusId": "",
          "userName": "",
          'mobileNo': '',
          "positions": [],
          'photo':''
        },
        dialogPeople: false,
        currentPage: 1,
        personalName: "",
        cancleData: {},
        tableData: [], //树形图初始数据
        orgId: "",
        addUser: [], //下拉人员初始化
        addGender: [], //下拉性别
        personalSearch: '', //人员搜索框,
        initialeditData: {},
        justJobEdit: '',
        fileList: [],
      }
    },
    watch: {
      filterText(val) { //树查询
        if (val) {
          organizationSearch(val).then(res => {
            this.removeTip() //移除默认提示
            this.deepChild(res.data.data);
            this.dataTree = res.data.data
          })
        } else {
          this.filterText = ""
          this.keyTree += 1
        }
      }
    },
    created() {
      this.Authorization = this.getCookie('Authorization')
      window.onresize = () => {
        this.$refs.tableData.doLayout()
      }
    },
    methods: {
      /*移除默认提示 */
      removeTip() {
        let msgs = document.getElementsByClassName("el-message")
        for (let i = 0, len = msgs.length; i < len; i++) {
          msgs[i].style.display = "none";
        }
      },
      getCookie(cname) { // 获取cookie
        var name = cname + "="
        var ca = document.cookie.split(';')
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i].trim()
          if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
        }
        return ""
      },
      deepChild(val) { /* 递归遍历树形数据源 */
        let $this = this;
        if (val && Array.isArray(val) && val.length) {
          val.forEach(item => {
            if (typeof item === 'object') {
              item.orgId = item.id;
              item.orgName = item.name;
              $this.deepChild(item.children);
            }
          });
        }
      },
      loadNode(node, resolve) { //树形图父节点
        if (node.level === 0) {
          organizationRoot().then(res => {
            res.data.data.forEach(e => {
              e.leaf = e.isLeaf == 'y' ? true : false;
            });
            resolve(res.data.data);
            this.orgId = res.data.data[0].orgId
            this.$refs.tree.setCurrentKey(this.orgId);
            this.treeExpandedKey = [this.orgId];
            this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
          }).catch(res => {
            resolve([])
          })
        } else {
          let id = node.data.orgId
          let datas = {
            'id': id,
            'page': 0,
            'size': 0
          }
          organizationParent(datas).then(res => {
            res.data.data.records.forEach(e => {
              e.leaf = e.isLeaf == 'y' ? true : false;
            });
            resolve(res.data.data.records)
          }).catch(res => {
            resolve([])
          })
        }
      },
      dataTable(idTable, page, size, data) { //表格数据 方法
        orgEmpOrgOrgId(idTable, page, size, data).then(res => {
          this.tableData = []
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          res.data.data.records.forEach(item => {
            if (item.positions.length == 0) {
              return
            } else {
              let ary = []
              item.positions.forEach(item => {
                ary.push(item.shortName)
              })
              item.postionsAry = ary
            }
          })
          setTimeout(() => {
            this.$refs.tableData.doLayout() //重绘表格宽度，解决表头对不齐的问题
          }, 0);
        }).catch(res => {})
      },
      handleJob(id) { //获取所有岗位
        orgPositionListsDatas(id).then(res => {
          if (res.data.code == 10000) {
            return res.data.data
          }
        }).catch(res => {})
      },
      justSearchPeople() {
        this.searchPeople(1, 20)
      },
      searchPeople(currentPage, pageSize) { //搜索员工
        let data = {
          'empCode': this.personalSearch,
          'empName': this.personalSearch
        }
        this.dataTable(this.orgId, currentPage, pageSize, data)
      },
      initSearchList() {
        this.personalSearch = '';
        this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
      },
      excelDownload() { //人员导入模板下载
        this.axios({
          url: '/org/employee/downExcelTemplate',
          method: 'GET',
          responseType: 'blob',
        }).then((response) => {
          let fileName = response.headers['content-disposition']
          let realFileName = ""
          realFileName = fileName.substring(40, fileName.length - 1);
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', realFileName);
          document.body.appendChild(link);
          link.click();
        })
      },
      beforeAvatarUpload(file) { //头像上传之前
        var imageClass = file.name.substring(file.name.lastIndexOf(".") + 1);
        const imageStyle =
          imageClass === "jpg" ||
          imageClass === "JPG" ||
          imageClass === "png" ||
          imageClass === "PNG" ||
          imageClass === "bpm" ||
          imageClass === "BPM" ||
          imageClass === "JPEG" ||
          imageClass === "jpeg"
        if (!imageStyle) {
          Message({
            message: "上传图片只能是jpg / png / bpm/jpeg格式!",
            type: "error"
          })
        } else {
          this.photos = file.url
          return imageStyle
        }

      },
      photoSuccess(res, file, fileList) { //头像上传成功
        if (res.code == 10000) {
          this.realPhotoUrL = res.data[0].filePth
          this.photos = attachPath+res.data[0].filePth
          //this.photos = URL.createObjectURL(file.raw);
          console.log(fileList,5050)
          this.photoFileList =fileList
          Message({
            type: 'success',
            message: '头像上传成功！'
          })
        }
      },
      handleAvatarChange(file, fileList) { //文件发生改变
        var imageClass = file.name.substring(file.name.lastIndexOf(".") + 1);
        const imageStyle =
          imageClass === "jpg" ||
          imageClass === "JPG" ||
          imageClass === "png" ||
          imageClass === "PNG" ||
          imageClass === "bpm" ||
          imageClass === "BPM" ||
          imageClass === "JPEG" ||
          imageClass === "jpeg";
        if (!imageStyle) {
          fileList.pop()
          this.photoFileList = fileList
        } else {
          this.photoFileList = fileList.slice(-1)
          this.photos = file.url
          return imageStyle
        }
      },
      handleRemove(file, fileList) { //头像移除
        let data = file.response.data[0].filePth
        photoDel([data]).then(res => {
          if (res.data.code == 10000) {
            this.photos = ''
            this.photoFileList = []
            Message({
              type: 'success',
              message: '头像移除成功！'
            })
          }
        })
      },
      handleSuccess(response, file, fileList) {
        if (!response.data) {
          Message({
            message: response.msg,
            type: 'error'
          });
          this.fileList = [];
        } else {
          Message({
            message: '上传成功',
            type: 'success'
          });
          this.fileList = [];
        }
      },
      handlePreview(file) {
        console.log(file);
      },
      handleNodeClick(data) { //点击树形图 表格数据加载
        this.currentPage = 1;
        this.orgId = data.orgId
        this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
      },
      filterNode(value, data) { //树状图
        if (!value) return true;
        return data.orgName.indexOf(value) !== -1
      },
      employeeInfo(data) { //人员详情 接口暂时有问题
        employeeEmpId(data).then(res => {
          if (res.data.code == 10000) {
            this.editData = res.data.data.records
          }
        })
      },
      handleEdit(index, row) { //编辑
        this.dialogVisible = true;
        this.changeTitle = "编辑人员"
        this.getAddUser()
        this.photos = attachPath+row.photo.slice(row.photo.indexOf('/')+1)
       console.log(this.photos,5555)
        this.$nextTick(() => {

          this.editData = JSON.parse(JSON.stringify(row))
          this.initialeditData = JSON.parse(JSON.stringify(this.editData))
        })
      },
      handlePeopleEdit(index, row) { //人员岗位编辑
        this.dialogPeople = true
        this.justJobEdit = 'true'
        this.$nextTick(() => {
          this.editData = JSON.parse(JSON.stringify(row))
          this.initialeditData = JSON.parse(JSON.stringify(this.editData))
        })
      },
      peopleDialog(data) { //父传子事件
        this.dialogPeople = data
      },
      jobEdit(data) {
        this.editData.positions = data
      },
      tagAdd() {
        if (this.changeTitle == '新增人员') {
          this.$refs.addPositons.clearValidate()
        }
        this.dialogPeople = true
        this.justJobEdit = false
        this.$nextTick(() => {
          this.initialeditData = JSON.parse(JSON.stringify(this.editData))
        })
      },
      handleClose() { //编辑弹框关闭
        this.handleCheckClose('editData')
      },
      handleUp(index, row, isUp) { //向上移动
        if (isUp == 'up') {
          let data = {
            'empId': row.empId,
            'orgId': this.orgId,
            'type': 1
          }
          upDownRemove(data).then(res => {
            this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
          })
        } else {
          let data = {
            'empId': row.empId,
            'orgId': this.orgId,
            'type': 2
          }
          upDownRemove(data).then(res => {
            this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
          })
        }
      },
      handleCheckClose(formName) { //弹框关闭
        this.dialogVisible = false;
        if (this.changeTitle == '新增人员') {
          this.$refs[formName].clearValidate()
          this.photoFileList = []
        }
      },
      handleCheck(formName) { //弹框确认
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let ids = []
            this.editData.positions.forEach(item => {
              ids.push(item.positionId)
            })
            if (this.changeTitle == '新增人员') {
              this.editData.empId = ''
            }
            employeeAddOrEdit({
              "photo": this.realPhotoUrL,
              "empId": this.editData.empId,
              "empName": this.editData.empName,
              "empCode": this.editData.empCode,
              "empStatus": this.editData.empStatusId,
              "empStatusId": this.editData.empStatus,
              "orgId": this.orgId,
              "gender": this.editData.genderId,
              "genderId": this.editData.gender,
              "userName": this.editData.userName,
              "mobileNo": this.editData.mobileNo,
              "positions": ids
            }).then(res => {
              if (res.data.code == 10000) {
                this.dialogVisible = false;
                this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
                Message({
                  type: 'success',
                  message: '人员保存成功！'
                })
              }
            }).catch()
          } else {
            return false;
          }
        })
      },
      handleAdd(formName) { //新增按钮
        this.dialogVisible = true
        this.photoFileList = []
        this.changeTitle = "新增人员"
        this.getAddUser()
        this.editData = {
          "empName": "",
          "empCode": "",
          "genderId": "",
          "empStatusId": "",
          "userName": "",
          'mobileNo': '',
          "positions": [],
          "photo": ''
        }
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
        }
      },
      getAddUser() { //弹框人员下拉
        comboBoxDataSelect('35690664d1884758ad0414fe80b2ffb6').then(res => { //人员状态
          this.addUser = res.data.data
        }).catch(res => {
          resolve([])
        })
        comboBoxDataSelect('8051ef75890846f495d95db1f27fdd45').then(res => { //性别
          this.addGender = res.data.data
        }).catch(res => {
          resolve([])
        })
      },
      handleSizeChange(val) { //每页条数
        if (this.personalSearch != '') {
          this.searchPeople(this.currentPage, val)
        } else {
          this.dataTable(this.orgId, this.currentPage, val, {})
        }
      },
      handleCurrentChange(val) { //当前页数
        if (this.personalSearch != '') {
          this.searchPeople(val, this.pageSize)
        } else {
          this.dataTable(this.orgId, val, this.pageSize, {})
        }
      },
      handleBefore(file) { //文件上传之前
        let fileTextClass = file.name.substring(file.name.lastIndexOf(".") + 1);
        const fileTextStyle = fileTextClass === "xlsx" || fileTextClass === "xls"
        if (!fileTextStyle) {
          Message({
            message: "上传文件只能是xlsx / xls 格式!",
            type: "error"
          })
        }
      },
      refreshTable() {
        Message({
          type: 'success',
          message: '岗位分配成功！'
        })
        this.dataTable(this.orgId, this.currentPage, this.pageSize, {})
      }
    }
  };
</script>

<style lang="scss">
  .el-tag {
    margin-bottom: 3px !important;
  }

  .el-card__body {
    position: relative;
  }

  .pagination.el-pagination {
    position: absolute;
    bottom: 5px;
    left: 15px;
  }

  .el-form-tag .el-tag {
    margin-bottom: 10px;
    margin-left: 0 !important;
    margin-right: 10px !important;
  }

  .table-title-word {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
